<template>
  <view>
    <!-- 搜索框 -->
    <yg-search />
    <!-- tab栏 -->
    <u-tabs
      :list="list"
      :is-scroll="false"
      :current="current"
      @change="change"
      active-color="#EA4350"
      bar-width="200"
      bar-height="5"
      bold="false"
    ></u-tabs>
    <view v-if="current === 0">
      <scroll-view
        class="scroll"
        scroll-y="true"
        @scrolltolower="handleReachBottom"
        refresher-enabled
        @refresherrefresh="handlePullRefresh"
        :refresher-triggered="trigger"
      >
        <good-item v-for="item in goodList" :key="item.goods_id" :good="item" />
      </scroll-view>
    </view>
    <view v-if="current === 1">销量</view>
    <view v-if="current === 2">价格</view>
  </view>
</template>

<script>
import GoodItem from './components/good-items.vue'
export default {
  components: {
    GoodItem,
  },
  data () {
    return {
      list: [{
        name: '综合'
      }, {
        name: '销量'
      }, {
        name: '价格',
      }],
      current: 0,
      // 商品列表
      goodList: [],
      trigger: false
    }
  },
  onLoad (options) {
    console.log(options)
    // 为了方便修改接口参数，封装成全局变量
    this.params = {
      query: '',
      cid: options.cid || 6,
      pagenum: 1,
      pagesize: 10
    }
    this.getGoodsSearch()
  },
  //  页面滚动条到底部会触发
  //  onReachBottom () {
  //       console.log('滚到底了')
  //     },
  methods: {
    change (index) {
      this.current = index
    },
    async getGoodsSearch () {
      const res = await this.$u.get('/goods/search', this.params)
      console.log(res.message)
      // this.goodList = res.message.goods
      this.goodList = [...this.goodList, ...res.message.goods]
      this.total = res.message.total
    },
    // 滚动条滚到底触发
    handleReachBottom () {
      // console.log('滚到底了')
      // 判断 还有没有下一页数据 
      // 返回的数据total 数 大于 当前数据列表的length值
      if (this.total > this.goodList.length) {
        this.params.pagenum++
        this.getGoodsSearch()
      } else {
        uni.showToast({
          title: '没有更多数据了',
          icon: "none"
        })
      }

    },
    // 容器级别的下拉刷新
    async handlePullRefresh () {
      // 下拉执行设置新的下拉状态
      this.trigger = true
      // console.log('下拉刷新了')
      this.goodList = []
      this.params.pagenum = 1
      await this.getGoodsSearch()  // 异步代码 需要 await 等待请求回来才去执行下面的代码
      // 等待请求成功之后 才去关闭下拉状态
      this.trigger = false
      // console.log('下拉关闭')
    }
  }
}
</script>

<style scoped lang="scss">
.scroll {
  height: calc(100vh - 182rpx);
}
</style>